#coding: utf-8

from invenio.dbquery import run_sql

def format(bfo, dbquery_field="980__a"):
	"""
	Print collection name from the database according to actual language (default is Czech)
	
	@dbquery_field enter field containing dbquery entry e.g. 980__a is default for collection:something
	"""
	
	q = bfo.field(dbquery_field)
	res = run_sql("""SELECT ln, value FROM `collection` 
					 LEFT JOIN collectionname ON collectionname.id_collection = collection.id 
					 WHERE dbquery LIKE '%%:%s'""" % q)
					 
	parent = run_sql("""SELECT id_dad FROM collection LEFT JOIN collection_collection ON id=id_son WHERE dbquery LIKE '%%:%s'""" % q)
	 
	names = {}
	for r in res:
		names[r[0]] = r[1]
	
	if bfo.lang not in names:
		if names.has_key("cs"):
			return names["cs"] 
		else:
			res = run_sql("""SELECT name FROM `collection` 
					 		 WHERE dbquery LIKE '%%:%s'""" % q)
			if res:
				return res[0][0] 
			else:
				return ""
	else:
		return names[bfo.lang]
		
if __name__ == "__main__":
	from invenio.bibformat_engine import BibFormatObject
	print format(BibFormatObject(42403), "998__a")
